package com.micro.ai.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.auth.entity.LoginLog;
import com.micro.ai.auth.mapper.LoginLogMapper;
import com.micro.ai.commons.domain.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
/**
 * 登录日志控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/logs")
@Tag(name = "日志审计", description = "登录日志查询、审计等操作")
public class LoginLogController {

    @Autowired
    private LoginLogMapper loginLogMapper;

    /**
     * 分页查询登录日志
     */
    @GetMapping("/login")
    @PreAuthorize("hasAuthority('log:view')")
    @Operation(summary = "分页查询登录日志", description = "根据条件分页查询登录日志")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Page<LoginLog>> listLoginLogs(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "登录方式") @RequestParam(required = false) String loginType,
            @Parameter(description = "登录状态") @RequestParam(required = false) String status) {
        
        Page<LoginLog> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LoginLog> query = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(userId)) {
            query.eq(LoginLog::getUserId, userId);
        }
        if (StringUtils.hasText(username)) {
            query.like(LoginLog::getUsername, username);
        }
        if (StringUtils.hasText(tenantId)) {
            query.eq(LoginLog::getTenantId, tenantId);
        }
        if (StringUtils.hasText(loginType)) {
            query.eq(LoginLog::getLoginType, loginType);
        }
        if (StringUtils.hasText(status)) {
            query.eq(LoginLog::getStatus, status);
        }

        query.orderByDesc(LoginLog::getCreatedAt);

        Page<LoginLog> result = loginLogMapper.selectPage(page, query);
        return ApiResponse.success(result);
    }

    /**
     * 根据ID获取登录日志详情
     */
    @GetMapping("/login/{logId}")
    @PreAuthorize("hasAuthority('log:view')")
    @Operation(summary = "获取登录日志详情", description = "根据ID获取登录日志详细信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = LoginLog.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "登录日志不存在")
    })
    public ApiResponse<LoginLog> getLoginLogById(
            @Parameter(description = "日志ID", required = true) @PathVariable String logId) {
        LoginLog log = loginLogMapper.selectById(logId);
        if (log == null) {
            return ApiResponse.error("A0404", "登录日志不存在");
        }
        return ApiResponse.success(log);
    }

    /**
     * 获取用户最近的登录日志
     */
    @GetMapping("/login/user/{userId}/recent")
    @PreAuthorize("hasAuthority('log:view')")
    @Operation(summary = "获取用户最近登录日志", description = "获取指定用户最近N条登录日志")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<java.util.List<LoginLog>> getUserRecentLoginLogs(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId,
            @Parameter(description = "数量", example = "10") @RequestParam(defaultValue = "10") int limit) {
        
        LambdaQueryWrapper<LoginLog> query = new LambdaQueryWrapper<>();
        query.eq(LoginLog::getUserId, userId);
        query.orderByDesc(LoginLog::getCreatedAt);
        query.last("LIMIT " + limit);

        java.util.List<LoginLog> logs = loginLogMapper.selectList(query);
        return ApiResponse.success(logs);
    }

    /**
     * 统计登录日志
     */
    @GetMapping("/login/stats")
    @PreAuthorize("hasAuthority('log:view')")
    @Operation(summary = "统计登录日志", description = "统计登录成功/失败次数")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<java.util.Map<String, Object>> getLoginStats(
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "开始时间（yyyy-MM-dd HH:mm:ss）") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间（yyyy-MM-dd HH:mm:ss）") @RequestParam(required = false) String endTime) {
        
        LambdaQueryWrapper<LoginLog> successQuery = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<LoginLog> failedQuery = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(userId)) {
            successQuery.eq(LoginLog::getUserId, userId);
            failedQuery.eq(LoginLog::getUserId, userId);
        }
        if (StringUtils.hasText(tenantId)) {
            successQuery.eq(LoginLog::getTenantId, tenantId);
            failedQuery.eq(LoginLog::getTenantId, tenantId);
        }
        if (StringUtils.hasText(startTime)) {
            successQuery.ge(LoginLog::getCreatedAt, startTime);
            failedQuery.ge(LoginLog::getCreatedAt, startTime);
        }
        if (StringUtils.hasText(endTime)) {
            successQuery.le(LoginLog::getCreatedAt, endTime);
            failedQuery.le(LoginLog::getCreatedAt, endTime);
        }

        successQuery.eq(LoginLog::getStatus, "success");
        failedQuery.eq(LoginLog::getStatus, "failed");

        long successCount = loginLogMapper.selectCount(successQuery);
        long failedCount = loginLogMapper.selectCount(failedQuery);

        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        stats.put("successCount", successCount);
        stats.put("failedCount", failedCount);
        stats.put("totalCount", successCount + failedCount);
        stats.put("successRate", successCount + failedCount > 0 ? 
                String.format("%.2f%%", successCount * 100.0 / (successCount + failedCount)) : "0.00%");

        return ApiResponse.success(stats);
    }
}

